import {SessionStorage} from "@/utils/session-storage";

export class Tool{
    public  SESSION_KEY_LOGIN_MEMBER:string = "SESSION_KEY_LOGIN_MEMBER"; // 登录信息
    public  SESSION_KEY_LOGIN_USER:string = "SESSION_KEY_LOGIN_USER"; // 登录信息

    public  sessionStorage:SessionStorage=SessionStorage.getInstance()
    /**
     * 单例变量声明
     *
     * @private
     * @static
     * @type {Http}
     * @memberof Http
     */
    private static Tool: Tool;

    public static getInstance(): Tool {
        if (!Tool.Tool) {
            Tool.Tool = new Tool();
        }
        return this.Tool;
    }
  /**
   * 空校验 null或""都返回true
   */
 public isEmpty (obj:any) {
    if ((typeof obj == 'string')) {
      return !obj || obj.replace(/\s+/g, "") == ""
    } else {
      return (!obj || JSON.stringify(obj) === "{}" || obj.length === 0);
    }
  }

  /**
   * 非空校验
   */
  public isNotEmpty (obj:any) {
    return !this.isEmpty(obj);
  }

  /**
   * 长度校验
   */
  public isLength (str:any, min:any, max:any) {
    return str.trim(str).length >= min && str.trim(str).length <= max;
  }

  /**
   * 时间格式化，date为空时取当前时间
   */
  public dateFormat (format:any, date:any) {
    let result;
    if (!date) {
      date = new Date();
    }
    const option:any = {
      "y+": date.getFullYear().toString(),        // 年
      "M+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "h+": date.getHours().toString(),           // 时
      "m+": date.getMinutes().toString(),         // 分
      "s+": date.getSeconds().toString()          // 秒
    };
    for (let i in option) {
      result = new RegExp("(" + i + ")").exec(format);
      if (result) {
        format = format.replace(result[1], (result[1].length == 1) ? (option[i]) : (option[i].padStart(result[1].length, "0")))
      }
    }
    return format;
  }

  /**
   * 移除对象数组中的对象
   * @param array
   * @param obj
   * @returns {number}
   */
  public removeObj (array:any, obj:any) {
    let index = -1;
    for (let i = 0; i < array.length; i++) {
      if (array[i] === obj) {
        array.splice(i, 1);
        index = i;
        break;
      }
    }
    return index;
  }

  /**
   * 10进制转62进制
   * @param number
   * @returns {string}
   * @private
   */
  public _10to62 (number:any) {
    let chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ';
    let radix = chars.length;
    let arr = [];
    do {
      let mod = number % radix;
      number = (number - mod) / radix;
      arr.unshift(chars[mod]);
    } while (number);
    return arr.join('');
  }

  /**
   * 保存登录用户信息
   */
  public setLoginUser (loginUser:any) {
    this.sessionStorage.set(this.SESSION_KEY_LOGIN_USER, loginUser);
  }

  /**
   * 获取登录用户信息
   */
  public getLoginUser () {
    return this.sessionStorage.get(this.SESSION_KEY_LOGIN_USER) || {};
  }
  /**
   * 移除登录用户信息
   * @returns {*|void}
   */
 public removeLoginUser(){
    return this.sessionStorage.remove(this.SESSION_KEY_LOGIN_USER);
  }
  /**
   * 保存登录用户信息
   */
  public setLoginMember (loginMember:any) {
    this.sessionStorage.set(this.SESSION_KEY_LOGIN_MEMBER, loginMember);
  }

  /**
   * 获取登录用户信息
   */
  public getLoginMember () {
    return this.sessionStorage.get(this.SESSION_KEY_LOGIN_MEMBER) || {};
  }
  /**
   * 移除登录用户信息
   * @returns {*|void}
   */
  public removeLoginMember(){
    return this.sessionStorage.remove(this.SESSION_KEY_LOGIN_USER);
  }



  /**
   * 随机生成[len]长度的[radix]进制数
   * @param len
   * @param radix 默认62
   * @returns {string}
   */
  public uuid (len:any, radix:any=62) {
    let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    let uuid = [];
    radix = radix || chars.length;

    for (let i = 0; i < len; i++) {
      uuid[i] = chars[0 | Math.random() * radix];
    }

    return uuid.join('');
  }

  /**
   * 对象数组按key对应的值排序
   * @param array
   * @param key
   * @returns {*}
   */
 public sortAsc (array:any, key:any) {
    return array.sort(function (obj1:any, obj2:any) {
      let val1 = obj1[key];
      let val2 = obj2[key];
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    });
  }
  /**
   * 下载文件
   * @param res
   */
  public downloadFile(res:any) {
    let blob = new Blob([res.data]); //res为从后台返回的数据
    var fileName = res.headers['content-disposition'].split('filename=').pop();
    if ('msSaveOrOpenBlob' in navigator) {
        let navigator:any=window.navigator;
        navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
      const elink = document.createElement('a');
      elink.download = decodeURI(fileName);
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);
      document.body.removeChild(elink);
    }

  }

    /**
     * 深度copy
     * @param data
     */
  public deepClone(data: any): any {
        // 获取传入拷贝函数的数据类型
        const type = this.typeOf(data)
        // 定义一个返回any类型的数据
        let reData: any;
        // 递归遍历一个array类型数据，
        if (type === "array") {
            reData = []
            for (let i = 0; i < data.length; i++) {
                reData.push(this.deepClone(data[i]))
            }
        } else if (type === "object") { //递归遍历一个object类型数据
            reData = {}
            for (const i in data) {
                reData[i] = this.deepClone(data[i])
            }
        }
        else {
            // 返回基本数据类型
            return data
        }
        // 将any类型的数据return出去，作为deepClone的结果
        return reData
    }
   private typeOf(obj: any): any {
        const toString: any = Object.prototype.toString
        const map: any = {
            "[object Boolean]": "boolean",
            "[object Number]": "number",
            "[object String]": "string",
            "[object Function]": "function",
            "[object Array]": "array",
            "[object Date]": "date",
            "[object RegExp]": "regExp",
            "[object Undefined]": "undefined",
            "[object Null]": "null",
            "[object Object]": "object"
        }
        return map[toString.call(obj)]
    }

}
declare module "vue/types/vue" {
    interface Vue {
        /**
         * Http net 对象
         *
         * @type {Http}
         * @memberof Vue
         */
        $Tool: Tool;
    }
}


